
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using mymvc_individual.Models;
using mymvc_individual.Services;
using mymvc_individual.Data;

namespace mymvc_individual.Controllers
{
    [Authorize]
    public class TodoController : Controller
    {
        private readonly ITodoItemService _todoItemService;
        private readonly UserManager<ApplicationUser> _userManager;

        public TodoController(ITodoItemService todoItemService, UserManager<ApplicationUser> user)
        {
            _todoItemService = todoItemService;
            _userManager = user;
        }

        public async Task<IActionResult> Index()
        {
            var currentUser = await _userManager.GetUserAsync(User);

            if (currentUser == null) return Challenge();

            var items = await _todoItemService.GetIncompleteItemsAsync(currentUser);

            var model = new TodoViewModel(){
                Items = items
            };

            return View(model);
        }

        [ValidateAntiForgeryToken]
        public async Task<IActionResult> AddItem(TodoItem newItem)
        {
            if(!ModelState.IsValid){
                return RedirectToAction("Index");
            }

            var currentUser = await _userManager.GetUserAsync(User);

            if (currentUser == null) return Challenge();

            if(! await _todoItemService.AddItemAsync(newItem, currentUser)){
                return BadRequest("could not add the item");
            }

            return RedirectToAction("Index");
        }

        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteItem(TodoItem newItem)
        {
            if(!ModelState.IsValid){
                return RedirectToAction("Index");
            }

            var currentUser = await _userManager.GetUserAsync(User);

            if (currentUser == null) return Challenge();

            if(! await _todoItemService.DeleteItemAsync(newItem.Title, currentUser)){
                return BadRequest("could not del the item");
            }

            return RedirectToAction("Index");
        }

        [ValidateAntiForgeryToken]
        public async Task<IActionResult> MarkDone(Guid id)
        {
            if(id == Guid.Empty){
                return RedirectToAction("Index");
            }

            var currentUser = await _userManager.GetUserAsync(User);

            if (currentUser == null) return Challenge();

            if(! await _todoItemService.MarkDoneAsync(id, currentUser)){
                return BadRequest("could not del the item");
            }

            return RedirectToAction("Index");
        }

    }

}